<template>
  <d2-container>
    <template slot="header">{{ title }}</template>
    <div style="margin-bottom:10px;font-size:14px">
      <span style="color:red">* </span>为必填项
    </div>
    <el-card shadow="never" class="d2-mb titleline">
      <template slot="header" style="height:66px;">
        <span class="title_x el-button--primary fl"></span>
        <p class="title_l fl">基础信息</p>
      </template>
      <el-form
        class="filter-container"
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="匹配名称" prop="match_name">
              <el-input
                placeholder="请输入内容"
                v-model="ruleForm.match_name"
                clearable
                :readonly="read"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="匹配ID">
              <el-input v-model="ruleForm.match_id" clearable :readonly="true">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="所属策略名称" prop="strategy_name">
              <el-input
                v-model="ruleForm.strategy_name"
                clearable
                :disabled="true"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="所属策略ID" prop="strategy_id">
              <el-input
                v-model="ruleForm.strategy_id"
                clearable
                :disabled="true"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="匹配类型" prop="match_type">
              <el-select
                v-model="ruleForm.match_type"
                placeholder="请选择"
                style="width:100%;"
                :disabled="true"
              >
                <el-option label="普通类型" value="1"></el-option>
                <el-option label="交割" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="匹配说明" prop="match_explain">
              <el-input
                class="resizeNone"
                style="width:139%"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }"
                placeholder="请输入内容"
                v-model="ruleForm.match_explain"
                :readonly="read"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card shadow="never" class="d2-mb titleline">
      <template slot="header" style="height:66px;">
        <span class="title_x el-button--primary fl"></span>
        <p class="title_l fl">策略信息</p>
      </template>
      <el-card shadow="never" class="d2-mb">
        <!-- <el-button type="default" size="mini" @click="addLine" v-if="flag">
          <d2-icon name="plus" />
          增行
        </el-button>
        <el-button
          type="default"
          size="mini"
          icon="el-icon-delete"
          @click="delstrategy"
          v-if="flag"
        >
          删行
        </el-button> -->
        <div style="margin-top:15px">
          <el-form :model="strategyData" ref="strategyFrom">
            <el-table
              :data="strategyData"
              border
              :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
              highlight-current-row
              @selection-change="strategySelect"
            >
              <el-table-column type="selection" width="40"> </el-table-column>
              <el-table-column type="index" label="序号"> </el-table-column>
              <el-table-column
                label="匹配数量*"
                prop="match_amount"
                width="140"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="scope.$index + '.match_amount'"
                    :rules="rules.match_amount"
                  >
                    <el-input
                      type="number"
                      readonly
                      v-model="scope.row.match_amount"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="matchable_amount"
                label="可匹配数量"
                width="140"
              >
              </el-table-column>
              <el-table-column prop="type" label="类型" width="140">
              </el-table-column>
              <el-table-column prop="name" label="品名" width="140">
              </el-table-column>
              <el-table-column prop="direction" label="方向" width="140">
              </el-table-column>
              <el-table-column prop="max_amount" label="最大数量" width="140">
              </el-table-column>
              <el-table-column
                prop="commodity_unit"
                label="单位"
                sortablewidth="140"
              >
              </el-table-column>
              <!-- <el-table-column prop="market" label="市场"   >
              </el-table-column> -->
              <el-table-column prop="currency" label="币种" width="140">
              </el-table-column>
              <el-table-column prop="brand" label="品牌" width="140">
              </el-table-column>
              <el-table-column prop="origin" label="产地" width="140">
              </el-table-column>
              <el-table-column prop="standard" label="规格" width="140">
              </el-table-column>
              <el-table-column prop="attribute" label="主属性" width="140">
              </el-table-column>
              <el-table-column
                prop="spare_text1"
                label="备用文本字段1"
                width="140"
              >
              </el-table-column>
              <el-table-column
                prop="spare_text2"
                label="备用文本字段2"
                width="140"
              >
              </el-table-column>
              <el-table-column
                prop="spare_text3"
                label="备用文本字段3"
                width="140"
              >
              </el-table-column>
              <el-table-column
                prop="spare_num1"
                label="备用数值字段1"
                width="140"
              >
              </el-table-column>
              <el-table-column
                prop="spare_num2"
                label="备用数值字段2"
                width="140"
              >
              </el-table-column>
              <el-table-column
                prop="spare_num3"
                label="备用数值字段3"
                width="140"
              >
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </el-card>
      <el-button
        type="primary"
        size="mini"
        style="float:right;margin:0 0 10px 10px;"
        @click="submitForm('ruleForm', 'strategyFrom', 'spotFrom')"
        v-if="flag"
      >
        保存
      </el-button>
    </el-card>
    <el-card shadow="never" class="d2-mb titleline">
      <template slot="header" style="height:66px;">
        <span class="title_x el-button--primary fl"></span>
        <p class="title_l fl">现货信息</p>
      </template>

      <el-card shadow="never" class="d2-mb">
        <el-button
          type="default"
          size="mini"
          @click="chooseDetails()"
          v-if="flag"
        >
          <d2-icon name="plus" />
          增行
        </el-button>
        <el-button
          type="default"
          size="mini"
          icon="el-icon-delete"
          v-if="flag"
          @click="delLine"
        >
          删行
        </el-button>
        <el-button
          type="primary"
          size="mini"
          :plain="true"
          @click="match"
          v-if="flag"
        >
          匹配</el-button
        >
        <div style="margin-top:15px">
          <el-form :model="spotData" ref="spotFrom">
            <el-table
              :data="spotData"
              border
              fit
              :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
              @selection-change="spotRow"
            >
              <el-table-column type="selection" width="40"> </el-table-column>
              <el-table-column type="index" label="序号"> </el-table-column>
              <el-table-column
                label="匹配数量*"
                prop="match_amount"
                width="140"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="scope.$index + '.match_amount'"
                    :rules="rules.match_amount"
                  >
                    <el-input
                      type="number"
                      @keyup.native="proving2($event)"
                      :readonly="read"
                      placeholder="请输入内容"
                      v-model="scope.row.match_amount"
                      @input="changMatch"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="matchable_amount"
                label="可匹配数量"
                width="140"
              >
              </el-table-column>
              <el-table-column prop="exp_vol" label="最大数量" width="140">
              </el-table-column>
              <el-table-column prop="name" label="品名" width="140">
              </el-table-column>
              <el-table-column prop="deal_no" label="合同号" width="140">
              </el-table-column>
              <el-table-column prop="exposure_no" label="敞口号" width="140">
              </el-table-column>
              <el-table-column prop="exp_type" label="敞口类型" width="140">
              </el-table-column>
              <el-table-column prop="direction" label="方向" width="140">
              </el-table-column>
              <el-table-column prop="invoice_vol" label="单据数量" width="140">
              </el-table-column>
              <el-table-column prop="price" label="价格" width="140">
              </el-table-column>
              <el-table-column prop="brand" label="品牌" width="140">
              </el-table-column>
              <el-table-column prop="origin" label="产地" width="140">
              </el-table-column>
              <el-table-column prop="standard" label="规格" width="140">
              </el-table-column>
              <el-table-column prop="attribute" label="主属性" width="140">
              </el-table-column>
              <el-table-column
                prop="spare_text1"
                label="备用文本字段1"
                width="140"
              >
              </el-table-column>
              <el-table-column
                prop="spare_text2"
                label="备用文本字段2"
                width="140"
              >
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </el-card>
    </el-card>
    <!-- 策略明细弹框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      title="策略明细"
    >
      <spot-futures-hedging
        :strategyInfo="ruleForm"
        :closeValue="'spotMatch_E'"
        @closeMoule="closeMoule"
      ></spot-futures-hedging>
    </el-dialog>
    <!-- 选择现货敞口弹框 -->
    <el-dialog
      :visible.sync="spotVisible"
      v-if="spotVisible"
      title="选择现货敞口"
    >
      <exposure-spot
        :closeValue="'exposureSpot'"
        :hedgingMethod="strategyData[0]"
        @closeSpot="closeSpot"
        :unable="spotData"
      ></exposure-spot>
    </el-dialog>
  </d2-container>
</template>

<script>
import spotFuturesHedging_M from "../../../tactical_management/master/model/spotFuturesHedging_M.vue";
import exposureSpot from "../model/exposureSpot.vue";
import { editMatchBase } from "@/api/url_info.js";
import { spotMatchStrategy } from "@/api/url_info.js";
import { spotMatchSpot } from "@/api/url_info.js";
import { spotMatchBase } from "@/api/url_info.js";
export default {
  //现货匹配-修改、查看
  name: "spotMatch_E",
  components: {
    "spot-futures-hedging": spotFuturesHedging_M,
    "exposure-spot": exposureSpot
  },
  data() {
    return {
      dialogVisible: false,
      spotVisible: false,
      title: "",
      old_match_amount: "",
      ruleForm: {
        //基础信息
        match_name: "",
        strategy_name: "",
        strategy_id: "",
        match_type: "",
        match_explain: "",
        match_id: "",
        creator: 1
      },
      rules: {
        match_name: [
          { required: true, message: "请输入匹配名称", trigger: "blur" }
        ],
        match_amount: [
          {
            trigger: "change",
            validator: (rule, value, callback) => {
              if (value != "") {
                if (
                  /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/.test(value) == false
                ) {
                  callback(new Error("请填写大于0的数字"));
                } else {
                  callback();
                }
              } else if (value == "") {
                callback(new Error("请填写匹配数量"));
              } else {
                callback();
              }
            }
          }
        ],
        match_type: [
          { required: true, message: "请选择匹配类型", trigger: "change" }
        ]
      },
      listRow: [],
      strategylist: [],
      spotData: [],
      strategyData: [],
      flag: true,
      read: false,
      isClick: false
    };
  },
  created() {
    this.spotMatchInfo();
  },
  methods: {
    changMatch() {
      this.isClick = false;
    },
    //网格信息
    spotMatchInfo() {
      spotMatchBase({ match_id: this.$route.query.match_id })
        .then(res => {
          let data = res.result.results[0];
          this.ruleForm = data;
          this.getStrategy();
          this.getSpot();
          if (this.$route.query.state === "check") {
            this.title = "现货匹配-查看";
            this.flag = false;
            this.read = true;
          } else if (this.$route.query.state === "alter") {
            this.title = "现货匹配-修改";
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //禁止输入负数
    proving2(e) {
      var keynum = window.event ? e.keyCode : e.which; //获取键盘码
      var keychar = String.fromCharCode(keynum); //获取键盘码对应的字符
      if (keynum == 189 || keynum == 109) {
        this.$message.warning("禁止输入负数");
        e.target.value = "";
      }
    },
    //查询策略信息
    async getStrategy() {
      await spotMatchStrategy({ match_id: this.ruleForm.match_id })
        .then(res => {
          let data = res.result.results;
          let strategyData = [];
          for (let i = 0; i < data.length; i++) {
            strategyData[i] = {
              match_amount: data[i]["match_amount"],
              id: data[i]["id"],
              strategy_id: data[i]["strategy_id"],
              hedging_method: data[i]["hedging_method"],
              trade_id: data[i]["trade_id"].id,
              match_id: data[i]["match_id"],
              matchable_amount: data[i]["matchable_amount"],
              type: data[i]["trade_id"].type,
              name: data[i]["trade_id"].name.name,
              direction: data[i]["trade_id"].direction,
              max_amount: data[i]["trade_id"].max_amount,
              commodity_unit: data[i]["trade_id"].commodity_unit,
              market: data[i]["trade_id"].market,
              currency: data[i]["trade_id"].currency,
              brand: data[i]["trade_id"].name.commodity_spot[0].brand,
              origin: data[i]["trade_id"].name.commodity_spot[0].origin,
              standard: data[i]["trade_id"].name.commodity_spot[0].standard,
              attribute: data[i]["trade_id"].name.commodity_spot[0].attribute
            };
          }
          this.strategyData = strategyData;
          this.old_match_amount = strategyData[0].match_amount;
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //查询现货信息
    async getSpot() {
      await spotMatchSpot({ match_id: this.ruleForm.match_id })
        .then(res => {
          let data = res.result.results;
          let spotData = [];
          for (let i = 0; i < data.length; i++) {
            spotData[i] = {
              match_amount: data[i]["match_amount"],
              match_id: data[i]["match_id"],
              trade_id: data[i]["trade_id"],
              strategy_id: data[i]["strategy_id"],
              matchable_amount: data[i]["matchable_amount"],
              name: data[i]["exposure_no"].commodity.name,
              deal_no: data[i]["exposure_no"].deal_no,
              exp_vol: data[i]["exposure_no"].exp_vol,
              exposure_no: data[i]["exposure_no"].exposure_no,
              exp_type: data[i]["exposure_no"].exp_type,
              direction: data[i]["exposure_no"].direction,
              invoice_vol: data[i]["exposure_no"].invoice_vol,
              price: data[i]["exposure_no"].price,
              brand: data[i]["exposure_no"].commodity.commodity_spot[0].brand,
              origin: data[i]["exposure_no"].commodity.commodity_spot[0].origin,
              standard:
                data[i]["exposure_no"].commodity.commodity_spot[0].standard,
              attribute:
                data[i]["exposure_no"].commodity.commodity_spot[0].attribute
            };
          }
          this.spotData = spotData;
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //匹配
    match() {
      this.isClick = true;
      if (this.strategyData.length > 0) {
        if (this.strategyData[0].strategy_id) {
          this.strategyData.match_amount = 0;
          let match_amount = 0;
          this.spotData.forEach(item => {
            if (item.match_amount * 100 > item.exp_vol * 100) {
              this.strategyData[0].match_amount = 0;
              this.$message({
                message: "匹配数量不能大于最大数量",
                type: "warning"
              });
            } else {
              if (
                item.name == this.strategyData[0].name &&
                item.direction == this.strategyData[0].direction
              ) {
                match_amount += item.match_amount * 1;
                console.log("555", this.spotData, match_amount);
                this.$delete(this.strategyData[0], "match_amount");
                this.$set(this.strategyData[0], "match_amount", match_amount);
              } else {
                this.$message({
                  message: "请匹配与策略信息相同品名和方向的数据",
                  type: "warning"
                });
              }
            }
          }, 0);
        } else {
          this.$message({
            message: "请输入匹配数量",
            type: "warning"
          });
        }
      } else {
        this.$message({
          message: "请选择一条策略信息",
          type: "warning"
        });
      }
    },
    //保存
    async submitForm(formName, strategyName, spotName) {
      this.strategyData.forEach(item => {
        item.strategy_id = this.ruleForm.strategy_id;
        item.match_id = this.ruleForm.match_id;
      });
      this.spotData.forEach(item => {
        item.strategy_id = this.ruleForm.strategy_id;
        item.match_id = this.ruleForm.match_id;
      });
      console.log("2343", this.strategyData);
      switch (this.ruleForm.match_type) {
        case "普通类型":
          this.ruleForm.match_type = "1";
          break;
        case "交割":
          this.ruleForm.match_type = "2";
          break;
      }
      let params = {
        operation: "MOD",
        //基础信息
        base_info: {
          creator: 1,
          match_name: this.ruleForm.match_name,
          strategy_name: this.ruleForm.strategy_name,
          strategy_id: this.ruleForm.strategy_id,
          match_type: this.ruleForm.match_type,
          match_id: this.ruleForm.match_id,
          match_explain: this.ruleForm.match_explain
        },
        //策略信息
        strategy_info: this.strategyData,
        //现货信息
        spot_info: this.spotData
      };
      const rule1 = new Promise((resolve, reject) => {
        this.$refs[formName].validate(valid => {
          if (valid) {
            resolve();
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      });
      const rule2 = new Promise((resolve, reject) => {
        this.$refs[strategyName].validate(valid => {
          if (valid) {
            resolve();
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      });
      const rule3 = new Promise((resolve, reject) => {
        this.$refs[spotName].validate(valid => {
          if (valid) {
            resolve();
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      });
      if (this.isClick) {
        Promise.all([rule1, rule2, rule3]).then(() => {
          if (this.spotData.length > 0 && this.strategyData.length > 0) {
            if (this.strategyData.length > 0) {
              if (
                Number(this.strategyData[0].match_amount) * 100 >
                Number(this.strategyData[0].matchable_amount) * 100 +
                  Number(this.old_match_amount) * 100
              ) {
                this.$message({
                  message: "匹配数量不能大于可匹配数量",
                  type: "warning"
                });
              } else {
                editMatchBase(params)
                  .then(res => {
                    this.$message({
                      message: res.result,
                      type: "success"
                    });
                    this.closeing.closePage(
                      this.$store.getters["d2admin/page/allPage"],
                      this.$store.getters["d2admin/page/currentPage"]
                    );
                    this.$router.push({
                      path: "/hedging_strategy/match_management?type=third"
                    });
                  })
                  .catch(err => {
                    this.$message.error(err.msg);
                  });
              }
            } else {
              editMatchBase(params)
                .then(res => {
                  this.$message({
                    message: res.result,
                    type: "success"
                  });
                  this.closeing.closePage(
                    this.$store.getters["d2admin/page/allPage"],
                    this.$store.getters["d2admin/page/currentPage"]
                  );
                  this.$router.push({
                    path: "/hedging_strategy/match_management?type=third"
                  });
                })
                .catch(err => {
                  this.$message.error(err.msg);
                });
            }
          } else {
            this.$message({
              message: "策略信息和现货信息不能为空",
              type: "warning"
            });
          }
        });
      } else {
        this.$message({
          message: "请先进行匹配",
          type: "warning"
        });
      }
    },
    //删行
    delLine() {
      this.isClick = false;
      let val = this.listRow;
      if (val.length > 0) {
        for (let i = 0; i < this.listRow.length; i++) {
          val.forEach((val, index) => {
            this.spotData.forEach((v, i) => {
              if (val.exposure_no === v.exposure_no) {
                this.spotData.splice(i, 1);
              }
            });
          });
        }
        this.$refs.table.clearSelection();
      } else {
        this.$message({
          message: "请选择删除数据",
          type: "warning"
        });
      }
    },
    delstrategy() {
      let val = this.strategylist;
      if (val.length > 0) {
        for (let i = 0; i < this.strategylist.length; i++) {
          val.forEach((val, index) => {
            this.strategyData.forEach((v, i) => {
              if (val.id === v.id) {
                this.strategyData.splice(i, 1);
              }
            });
          });
        }
      } else {
        this.$message({
          message: "请选择删除数据",
          type: "warning"
        });
      }
    },
    spotRow(val) {
      this.listRow = val;
    },
    //增行
    addLine() {
      this.isClick = false;
      if (this.ruleForm.strategy_id) {
        this.dialogVisible = true;
        let strategy_id = this.ruleForm.strategy_id;
        this.strategy_id = strategy_id;
      } else {
        this.$message({
          message: "请先选择策略",
          type: "warning"
        });
      }
    },
    //策略信息选中的一行数据
    strategySelect(val) {
      this.strategylist = val;
    },
    //策略明细弹框
    closeMoule(e) {
      if (e.length > 0) {
        e.forEach(item => {
          item.match_amount = 0;
          item.trade_id = item.id;
        });
        let data = [];
        data = e.concat(this.strategyData);
        this.strategyData = this.unique(data);
        this.dialogVisible = false;
      } else {
        this.$message({
          message: "请选择一条数据",
          type: "warning"
        });
      }
    },
    //去重
    unique(obj) {
      var uniques = [];
      var stringify = {};
      for (var i = 0; i < obj.length; i++) {
        var keys = Object.keys(obj[i]);
        keys.sort(function(a, b) {
          return Number(a) - Number(b);
        });
        var str = "";
        for (var j = 0; j < keys.length; j++) {
          str += JSON.stringify(keys[j]);
          str += JSON.stringify(obj[i][keys[j]]);
        }
        if (!stringify.hasOwnProperty(str)) {
          uniques.push(obj[i]);
          stringify[str] = true;
        }
      }
      uniques = uniques;
      return uniques;
    },
    //选择现货敞口弹框
    closeSpot(e) {
      if (e.length > 0) {
        e.forEach(item => {
          item.match_id = this.strategyData[0].match_id;
          item.trade_id = this.strategyData[0].trade_id;
        });
        this.spotData = e.concat(this.spotData);
        this.spotVisible = false;
      } else {
        this.$message({
          message: "请选择一条数据",
          type: "warning"
        });
      }
    },
    //选择现货敞口(增行)
    chooseDetails() {
      if (this.strategyData.length > 0) {
        this.spotVisible = true;
      } else {
        this.$message({
          message: "请先添加一条策略信息",
          type: "warning"
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.resizeNone {
  .el-textarea__inner {
    resize: none;
  }
}
.el-form-item {
  margin-bottom: 0px !important;
}
</style>
